package com.hdu.atomic;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicMarkableReference;

@Slf4j
public class ABAQuestionV2 {
    public static void main(String[] args) {
        AtomicMarkableReference<String> atomicMarkableReference =
                new AtomicMarkableReference<>("A", false);
        String prevS = atomicMarkableReference.getReference();
        boolean marked = atomicMarkableReference.isMarked();
        log.info("变量是否被修改过 : {}", marked ? "YES" : "NO");
        otherChange(atomicMarkableReference);
        boolean flag = atomicMarkableReference.compareAndSet(
                prevS, "B", marked, true
        );
        if (flag) {
            log.info("修改成功");
        }
        else {
            log.error("修改失败, 是否被修改过 : {}", atomicMarkableReference.isMarked() ? "YES" : "NO");
        }
    }


    static void otherChange(AtomicMarkableReference<String> atomicMarkableReference) {
        atomicMarkableReference.compareAndSet(
                "A", "B", false, true
        );
        atomicMarkableReference.compareAndSet(
                "B", "A", true, true
        );
    }
}
